<route lang="json5">
{
  style: {
    navigationBarTitleText: '我的报告',
    navigationBarBackgroundColor: '#FFFFFF',
  },
}
</route>

<template>
  <navbar text="我的报告" />
  <uv-sticky bgColor="#E50038" :offsetTop="safeAreaInsets?.top + 44 + stickyTop + 'px'">
    <view class="tabs">
      <uv-tabs
        :scrollable="true"
        :list="tabsList"
        :current="listIndex"
        keyName="name"
        lineColor="#cccccc"
        lineWidth="30"
        activeStyle="color: #cccccc;font-weight:600;"
        inactiveStyle="color: #ffffff;"
        itemStyle="height:84rpx;padding:0 24rpx;"
        customStyle="margin-bottom:14rpx;"
        @change="tabChange"
      ></uv-tabs>
    </view>
  </uv-sticky>
  <view class="scroll">
    <view class="public-background view-report">
      <scroll @scrollChange="scrollChange" :enabled="enabled">
        <view class="public-height"></view>
        <view class="list-box">
          <view class="list" v-for="(item, index) in reportGroup" :key="index">
            <view class="title" :class="{ 'title-diagnosed': item.diagnosed ? true : false }">
              <uv-text
                align="left"
                color="#000000"
                size="34rpx"
                :text="item.name || '--'"
              ></uv-text>
              <uv-text
                align="right"
                color="#666666"
                size="26rpx"
                :text="item.examDatetime"
              ></uv-text>
            </view>
            <view class="content">
              <wd-row>
                <wd-col :span="20">
                  <text class="header-font">
                    检查号：
                    <text class="info ml-16" :selectable="item.id ? true : false">
                      {{ item.id || '--' }}
                    </text>
                  </text>
                </wd-col>
                <wd-col :span="4" custom-class="col-right">
                  <text class="header-font">
                    <text class="info info-no-dia" :class="{ 'info-diagnosed': !!item.diagnosed }">
                      {{ item.diagnosed ? '已诊断' : '未诊断' }}
                    </text>
                  </text>
                </wd-col>
                <wd-col :span="24">
                  <text class="header-font">
                    检查项目：
                    <text class="info ml-16">{{ item.examItem || '--' }}</text>
                  </text>
                </wd-col>
                <wd-col :span="24" v-if="item.diagnosed">
                  <text class="header-font">
                    诊断时间：
                    <text class="info ml-16">{{ item.diagTime || '--' }}</text>
                  </text>
                </wd-col>
                <wd-col :span="24" v-else>
                  <text class="header-font">
                    上传时间：
                    <text class="info ml-16">{{ item.uploadTime || '--' }}</text>
                  </text>
                </wd-col>
                <wd-col :span="24">
                  <text class="header-font">
                    设备SN：
                    <text class="info ml-16" :selectable="item.sn ? true : false">
                      {{ item.sn || '--' }}
                    </text>
                  </text>
                </wd-col>
                <wd-col :span="24">
                  <text class="header-font">
                    戴机时长：
                    <text class="info ml-16">
                      {{ item.recordDays ? getVal(durationGroup, item.recordDays) : '--' }}
                    </text>
                  </text>
                </wd-col>
              </wd-row>
              <wd-row>
                <wd-col :span="24">
                  <text class="header-font">报告结论：</text>
                </wd-col>
                <wd-col :span="24">
                  <text class="ellipsis-4 info-font">
                    {{ item.reportContent }}
                  </text>
                </wd-col>
              </wd-row>
              <view class="button">
                <wd-button
                  custom-class="ml"
                  size="small"
                  v-if="item.diagnosed"
                  plain
                  @click="more(item)"
                >
                  查看报告单
                </wd-button>
              </view>
            </view>
          </view>
          <uv-load-more v-if="total >= 10" :status="status" />
        </view>
      </scroll>
    </view>
  </view>
</template>

<script lang="js" setup>
import navbar from '@/components/navbar'
import scroll from '@/components/scrollView'
import { getReportList, getPdf } from '@/service/index/default'
import { isLoginEd, getUser } from '@/utils/publicMethods'
import { durationGroup, getVal } from '@/utils/params'
const { safeAreaInsets } = uni.getWindowInfo()
const reportGroup = ref([])
const userInfo_ = ref({})
const isLogin = ref(false)
const enabled = ref(true)
const status = ref('loadmore')
const scrollHeight = ref('100%')
const total = ref(0)
let page = {
  pageNum: 1,
  pageSize: 10,
}

const tabsList = ref([
  { name: '全部', id: 0 },
  { name: '已诊断', id: 2 },
  { name: '未诊断', id: 1 },
])
const listIndex = ref(0)

onPageScroll((e) => {
  enabled.value = e.scrollTop > 10 ? false : true
})

const stickyTop = ref(0)
onShow(() => {
  const phoneType = uni.getDeviceInfo().platform
  stickyTop.value = phoneType === 'ios' ? -5 : 0
})

onLoad((option) => {
  const diagnosed = option?.diagnosed ? parseInt(option.diagnosed) : 0
  listIndex.value = tabsList.value.findIndex((o) => o.id === diagnosed)
  initData()
})

const tabChange = (e) => {
  listIndex.value = e.index
  initData()
}

const scrollChange = () => {
  initData()
}

const initData = () => {
  isLogin.value = isLoginEd()
  if (!isLogin.value) {
    reportGroup.value = []
    userInfo_.value = {}
    uni.showToast({
      title: '请前往登录',
      icon: 'none',
    })
    setTimeout(() => {
      const pages = getCurrentPages()
      if (pages.length > 1) {
        uni.navigateBack()
      } else {
        uni.switchTab({
          url: '/pages/home/index',
        })
      }
    }, 2000)
    return
  }
  page.pageNum = 1
  total.value = 0
  status.value = 'loadmore'
  userInfo_.value = getUser()
  uni.pageScrollTo({
    scrollTop: 0, // 滚动到页面的顶部
    duration: 300, // 滚动动画的时长，单位ms
  })
  getReportList_()
}

onReachBottom(async () => {
  if (reportGroup.value.length >= total.value) {
    status.value = 'nomore'
    return
  }
  page.pageNum++
  await getReportList_()
})

const getReportList_ = async () => {
  status.value = 'loading'
  const { data, code, error } = await getReportList({
    userId: userInfo_.value.userId,
    status: tabsList.value[listIndex.value].id,
    ...page,
  })
  if (code !== 200) {
    uni.showToast({
      title: `${error}`,
      icon: 'none',
    })
    status.value = 'nomore'
    return false
  }
  total.value = data?.count || 0
  if (!total.value) {
    status.value = 'nomore'
    uni.showToast({
      title: `暂无数据`,
      icon: 'none',
    })
    if (listIndex.value === 0) {
      setTimeout(() => {
        uni.navigateBack()
      }, 2000)
    }
    reportGroup.value = []
    return false
  }
  if (page.pageNum === 1) {
    reportGroup.value = data.data || []
  } else {
    reportGroup.value.push(...data.data)
  }
  status.value = reportGroup.value.length >= total.value ? 'nomore' : 'loadmore'
}

const more = async (row) => {
  if (!row?.id) {
    uni.showToast({
      title: '未获取到检查Id',
      icon: 'none',
    })
    return
  }
  // switch (uni.getDeviceInfo().platform) {
  //   case 'ios':
  //     uni.navigateTo({ url: `/pages/reportDetail/index?id=${row.id}` }, 1000)
  //     break
  //   default:
  uni.downloadFile({
    url: getPdf(row.id),
    success: (res) => {
      if (res.statusCode === 200) {
        const filePath = res.tempFilePath
        uni.openDocument({
          filePath: filePath,
          showMenu: true,
          success: () => {
            console.log('PDF 文件打开成功')
          },
          fail: (err) => {
            uni.showToast({
              title: '打开 PDF 文件失败',
              icon: 'none',
            })
          },
        })
      } else {
        uni.showToast({
          title: '下载 PDF 文件失败',
          icon: 'none',
        })
      }
    },
    fail: (err) => {
      uni.showToast({
        title: '下载文件失败',
        icon: 'none',
      })
    },
  })
  //     break
  // }
}

// -------------------微信分享----------------------
// 分享至好友/群聊
onShareAppMessage((res) => {
  return {
    title: '操作指引',
    path: getCurrentPages()[0].$page.fullPath,
    success: (res) => {},
    fail: (res) => {},
  }
})
</script>

<style lang="scss" scoped>
.tabs {
  padding: 0 20rpx;
}
.view-report {
  .list-box {
    min-height: calc(100vh - 88px - 58px);
    .list {
      margin-bottom: 20rpx;
      background: #ffffff;
      border-radius: 20rpx 20rpx;
      .title {
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: flex-start;
        padding: 14rpx 30rpx;
        background: linear-gradient(180deg, #eef5fd 0%, #dfecf6 100%);
        border-radius: 20rpx 20rpx 0rpx 0rpx;
      }
      .title-diagnosed {
        background: linear-gradient(180deg, #fff6f5 0%, #fde6e4 100%);
      }

      .content {
        padding: 30rpx 30rpx 20rpx 30rpx;
        :deep(.col-right) {
          text-align: center;
        }
        .header-font {
          font-family:
            PingFangSC,
            PingFang SC;
          font-size: 26rpx;
          font-weight: 500;
          line-height: 48rpx;
          color: #000000;
        }
        .info {
          margin-left: 10rpx;
          font-size: 26rpx;
          line-height: 48rpx;
          color: #666666;
        }
        .info-no-dia {
          color: #999999;
        }
        .info-diagnosed {
          color: #fa8385;
        }
        .info-font {
          padding: 0 8rpx;
          margin-bottom: 16rpx;
          font-size: 26rpx;
          line-height: 36rpx;
          color: #666666;
          text-indent: 1.5rem;
        }
        .button {
          margin-top: 16rpx;
          text-align: right;
          :deep(.ml) {
            margin-left: 20px;
          }
          :deep(.is-plain) {
            border: none;
          }
          :deep(.is-small) {
            padding: 0 32rpx;
          }
          :deep(.is-info) {
            color: #ffffff;
            background: #999999;
          }
        }
      }
    }
  }
}
</style>
